<template>
  <div>
    <el-upload class="upload-demo" action="http://localhost:8088/upload/file" drag multiple :file-list="fileList"
      :before-upload="beforeUpload" :on-success="handleAvatarSuccess">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar"> -->
    </el-upload>
    <!-- 图片预览模块 -->
    <el-dialog :visible.sync="dialogVisible">
      <img v-if="imageUrl" :src="imageUrl" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: '',
      fileList: [],
      dialogVisible: false
    }
  },
  methods: {
    // 文件上传前的校验:若返回 false 或者返回 Promise 且被 reject，则停止上传。
    // 作用：可以校验文件的格式或者文件大小
    beforeUpload(file) {
      const isJpg = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJpg) {
        this.$message.error('只能上传jpg格式的图片')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2M！')
      }
      // console.log(file)
      return isJpg && isLt2M
    },
    handleAvatarSuccess(response, file, fileList) {
      // console.log(response)
      // console.log(file)
      // console.log(fileList)
      this.imageUrl = URL.createObjectURL(file.raw)
      this.dialogVisible = true
    }
  }
}
</script>

<style scoped>
.avatar {
  width: 100%;
  /* height: 542px; */
  display: block;
}
</style>
